package org.eenie.appseed.ui.chat

import android.os.Bundle
import android.view.LayoutInflater
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import dev.chrisbanes.insetter.Insetter
import dev.chrisbanes.insetter.windowInsetTypesOf
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.eenie.appseed.databinding.FragmentChatBinding
import org.eenie.appseed.ui.chat.logic.ChatViewModel
import org.eenie.appseed.ui.chat.logic.ChatViewState
import org.eenie.core.base.viewbinding.BaseBindingFragment


class ChatFragment : BaseBindingFragment<FragmentChatBinding>() {


    private val mMsgAdapter = ChatMsgListAdapter()
    private val mModel: ChatViewModel by viewModels()

    companion object {
        fun newInstance() = ChatFragment()
    }


    override fun initUI(binding: FragmentChatBinding) {
        this.binding.rvChat.layoutManager = LinearLayoutManager(mContext)
        this.binding.rvChat.adapter = mMsgAdapter

        this.binding.laySwiper.setOnRefreshListener {
            mModel.fetchMsgList(isRefresh = true, isFirst = false)
        }

        mMsgAdapter.loadMoreModule.setOnLoadMoreListener {
            mModel.fetchMsgList(isRefresh = false, isFirst = false)
        }


        Insetter.builder()
            .marginBottom(windowInsetTypesOf(ime = true), animated = true)
            .applyToView(this.binding.layInput)



        mModel.state
            .onEach {
                render(it)
            }
            .launchIn(lifecycleScope)

        mModel.fetchMsgList(isFirst = true)
    }


    private fun render(state: ChatViewState) {
        when (state) {
            is ChatViewState.FetchMsgListSuccess -> {
                if (state.action == 0) {
                    mMsgAdapter.addData(0, state.list)
                    if (state.isFirst) {
                        scrollBottom()
                    }
                    binding.laySwiper.isRefreshing = false
                } else {
                    mMsgAdapter.addData(state.list)
                    mMsgAdapter.loadMoreModule.loadMoreComplete()
                }
            }

            else -> {

            }
        }
    }

    override fun providerBinding(inflater: LayoutInflater, savedInstanceState: Bundle?): FragmentChatBinding = FragmentChatBinding.inflate(inflater)


    private fun scrollBottom() {
        binding.rvChat.scrollToPosition(mMsgAdapter.itemCount - 1)
    }


}